package com.example.qsmx;

import com.example.qsmx.Util.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/qsmx-show")
public class ValueShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id == null || id.isEmpty()) {
            resp.sendRedirect("/WEB-INF/interface.jsp");
            return;
        }

        try {
            QSMXValue value = getQSMXById(Integer.parseInt(id));
            if (value == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "博客不存在");
                return;
            }
            req.setAttribute("qsmx", value);
            req.getRequestDispatcher("/WEB-INF/value-show.jsp").forward(req, resp);
        } catch (SQLException e) {
            throw new ServletException("获取博客详情时发生错误", e);
        }
    }

    private QSMXValue getQSMXById(int id) throws SQLException {
        String sql = "SELECT * FROM qsmxvalue WHERE `value-id` = ?";
        try (
                Connection conn = MyDBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)
        ) {
            pstmt.setInt(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    QSMXValue value = new QSMXValue(String.valueOf(rs.getInt("value-id")), rs.getString("value-tittle"), rs.getString("value-content"), rs.getString("value-create-time"), rs.getString("value-userAccount"), rs.getString("value-cover"));
                    return value;
                }
            }
        }
        return null;
    }
}
